package cn.t.facade.applet;

import cn.t.converter.order.WorkOrderDTOConverter;
import cn.t.core.exception.BizException;
import cn.t.model.order.WorkOrderDO;
import cn.t.model.order.WorkOrderDetailDO;
import cn.t.service.device.CargowaySkuService;
import cn.t.service.order.WorkOrderDetailService;
import cn.t.service.order.WorkOrderService;
import cn.t.service.user.CustomerFirmService;
import cn.t.vo.applet.AppletWorkOrderDetailVO;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.util.stream.Collectors.toList;

/**
 * 工单服务编排
 */
@Slf4j
@Service
@AllArgsConstructor
public class AppletWorkOrderFacade {

    private final WorkOrderService workOrderService;
    private final WorkOrderDetailService workOrderDetailService;
    private final WorkOrderDTOConverter workOrderDTOConverter;
    private final CustomerFirmService customerFirmService;

    private final CargowaySkuService cargowaySkuService;


    public AppletWorkOrderDetailVO detail(String workOrderSn) {

        WorkOrderDO workOrder = workOrderService.getWorkOrder(workOrderSn);

        if (workOrder == null) {
            throw new BizException(cn.t.enums.order.ErrorEnum.NO_DATA, "工单数据不存在");
        }

        WorkOrderDetailDO queryParam = new WorkOrderDetailDO();
        queryParam.setWorkOrderSn(workOrderSn);
        List<WorkOrderDetailDO> workOrderDetails = this.workOrderDetailService.findByModel(queryParam, cn.t.constants.CommonConstants.ZERO, Integer.MAX_VALUE, null, null);

        List<String> skuCodes = workOrderDetails.stream().map(WorkOrderDetailDO::getSkuCode).collect(toList());
        // 查询货道商品
        Map<String, List<String>> skuLocationMap = this.cargowaySkuService.getSkuLocation(skuCodes, null);

        Map<String, List<AppletWorkOrderDetailVO.Device>> deviceMap = new HashMap<>();
        skuLocationMap.forEach((skuCode, val) -> {
            List<AppletWorkOrderDetailVO.Device> devices = new ArrayList<>();
            val.forEach(location -> devices.add(new AppletWorkOrderDetailVO.Device(location.split(";")[0].split(":")[1], location.split(";")[1].split(":")[1])));
            deviceMap.put(skuCode, devices);
        });

        List<AppletWorkOrderDetailVO.WorkOrderSku> skuList = workOrderDetails.stream()
                .map(f -> this.workOrderDTOConverter.data2AppletDetailSku(f, deviceMap.get(f.getSkuCode()))).collect(toList());

        return this.workOrderDTOConverter.data2AppletDetailVo(workOrder, skuList);
    }

}

